from rest_framework.authentication import BaseAuthentication
from django.conf import settings
import jwt
from jwt.exceptions import ExpiredSignature, DecodeError
from rest_framework.exceptions import AuthenticationFailed
from users.models import User

from rest_framework.authentication import BaseAuthentication

class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.headers.get("Authorization")
        print("认证token:", token)
        if token.startswith("Bearer"):
            token = token.split(" ")[-1]
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
            print("解码出payload:", payload)
        except ExpiredSignature:
            raise AuthenticationFailed("token已过期")

        except DecodeError:
            raise AuthenticationFailed("非法的token")

        user = User.objects.filter(id=payload.get("uid")).first()
        return user, token